import { ref } from 'vue';
import { defineStore } from 'pinia';
import { useLockscreenStore } from './lockscreen';
import { useSSEStore } from './sse';
import type { RouteRecordRaw } from 'vue-router';
import { store } from '@/store';
import Api from '@/api/';
import { resetRouter } from '@/router';
import { generateDynamicRoutes } from '@/router/helper/routeHelper';

export const useUserStore = defineStore(
  'user',
  () => {
    const sseStore = useSSEStore();
    const lockscreenStore = useLockscreenStore();
    const redirect_url = ref<string>();
    const response_type = ref<string>();
    const code = ref<string>();
    const token = ref<string>();
    const perms = ref<string[]>([]);
    const menus = ref<RouteRecordRaw[]>([]);
    const userInfo = ref<Partial<API.UserEntity>>({});

    const sortMenus = (menus: RouteRecordRaw[] = []) => {
      return menus
        .filter((n) => {
          const flag = !n.meta?.hideInMenu;
          if (flag && n.children?.length) {
            n.children = sortMenus(n.children);
          }
          return flag;
        })
        .sort((a, b) => ~~Number(a.meta?.orderNo) - ~~Number(b.meta?.orderNo));
    };

    /** 清空登录态(token、userInfo...) */
    const clearLoginStatus = () => {
      redirect_url.value = '';
      response_type.value = '';
      code.value = '';
      token.value = '';
      perms.value = [];
      menus.value = [];
      userInfo.value = {};
      
      
      resetRouter();
      setTimeout(() => {
        localStorage.clear();
      });
    };
    /** 登录成功保存token */
    const setToken = (_token: string, _code: string) => {
      token.value = _token;
      code.value = _code;
    };
    const setRedirect = (_redirect_url: string, _response_type: string) => {
      redirect_url.value = _redirect_url;
      response_type.value = _response_type;
    };
    /** 登录 */
    const login = async (params: API.LoginDto) => {
      debugger
      try {
        const data = await Api.auth.authLogin(params);
        debugger;
        setToken(data.token, data.code);
        await afterLogin();
        lockscreenStore.setLock(false);
        lockscreenStore.saveLoginPwd(params.password);
      } catch (error) {
        return Promise.reject(error);
      }
    };
    const loginSSo = async (code) => {
      try {
        if (code) {
          const data = await Api.auth.wpsSSoLogin(code);
          setToken(data.toString());
        } else {
          setToken(
            'eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxMTExMTExMTExIiwic3ViIjoie1widXNlcm5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wiOm51bGwsXCJ1cGRhdGVkQXRcIjpudWxsfV0sXCJpZFwiOlwiZTZnUHBBd1ZKd2Q1TURFXCIsXCJjcmVhdGVkQXRcIjpudWxsLFwidXBkYXRlZEF0XCI6bnVsbH0iLCJpc3MiOiJ3cHMiLCJleHAiOjE3MTY3NzQyMzUsImlhdCI6MTcxNjE2OTQzNSwianRpIjoiZTZnUHBBd1ZKd2Q1TURFIn0.pVYGLV7hfMNcfotSeoBIDhrOvdUCt_Ea8XXME_tx2U8',
          );
        }

        await afterLogin();
        lockscreenStore.setLock(false);
      } catch (error) {
        return Promise.reject(error);
      }
    };
    /** 登录成功之后, 获取用户信息以及生成权限路由 */
    const afterLogin = async () => {
      try {
        debugger;
        const { accountProfile } = Api.account;
        // const wsStore = useWsStore();
        const userInfoData = await accountProfile();

        userInfo.value = userInfoData;
        await fetchPermsAndMenus();
        sseStore.initServerMsgListener();
      } catch (error) {
        return Promise.reject(error);
        // return logout();
      }
    };
    /** 获取权限及菜单 */
    const fetchPermsAndMenus = async () => {
      const { accountPermissions, accountMenu } = Api.account;
      // const wsStore = useWsStore();
      const [menusData, permsData] = await Promise.all([accountMenu(), accountPermissions()]);
      perms.value = permsData;
      const result = generateDynamicRoutes(menusData as unknown as RouteRecordRaw[]);
      menus.value = sortMenus(result);
    };
    /** 登出 */
    const logout = async () => {
      //await Api.account.accountLogout();
      sseStore.closeEventSource();
      clearLoginStatus();
    };

    return {
      code,
      token,
      perms,
      menus,
      userInfo,
      loginSSo,
      login,
      afterLogin,
      logout,
      clearLoginStatus,
      fetchPermsAndMenus,
      setRedirect,
    };
  },
  {
    persist: {
      paths: ['token','code'],
    },
  },
);

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
